# encoding: utf-8
'''
Created: 2014-04-28 12:46

@author: VAN
'''
import json
import logging
import random
import time
import urllib
import urllib2

from src.crawler import util


logging.basicConfig(level=logging.DEBUG,
                format='%(asctime)s %(filename)s [%(lineno)d] %(levelname)s %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S',
                filename='app.log',
                filemode='w')
logger = logging.getLogger();

class Baidu(object):
    def __init__(self, copyright_id, song_name, singer_name):
        self.uid = ''
        
        self.copyright_id = copyright_id;
        self.song_name = song_name;
        self.singer_name = singer_name;
        
        self.baidu_song_id = '';
        self.baidu_song_name = '';
        self.baidu_singer_name = '';
        self.baidu_lrc_url = '';
        self.baidu_mp3_url = '';
    
    def __str__(self):
        return str(self.uid) + '|' + str(self.copyright_id) + '|' + self.song_name + '|' + self.singer_name + '|' + str(self.baidu_song_id) + '|' + self.baidu_song_name + '|' + self.baidu_singer_name + '|' + str(self.baidu_lrc_url) + '|' + str(self.baidu_mp3_url) 
        
    
    def search(self):
        search_url_format = 'http://sug.music.baidu.com/info/suggestion?format=json&word={word}&version=2&from=0&callback=window.baidu.sug&_={timestamp}' + str(time.time()) + str(random.randint(0, 9))
        url = search_url_format.format(word=urllib2.quote(self.song_name + ' ' + self.singer_name), timestamp=str(time.time()) + str(random.randint(0, 9)))
        req = urllib2.Request(url=url)
        html = urllib2.urlopen(req).read()
        #   html='window.baidu.sug({"data":{"song":[{"songid":"1102942","songname":"\u5341\u5e74","artistname":"\u9648\u5955\u8fc5"}],"artist":[],"album":[]},"Pro":["song"]});';
        
        extract_json_regex = 'window.baidu.sug\((.*)\)'
        json_str = util.extractjson(html, extract_json_regex)
        if (json_str != '') :
            jo = json.loads(json_str)
            if len(jo['data']['song']) > 0:
                jsong = jo['data']['song'][0]
                self.baidu_song_id = jsong['songid']
                self.baidu_song_name = jsong['songname'].encode('utf-8')
                self.baidu_singer_name = jsong['artistname'].encode('utf-8')
                
    def extract_download_url(self):
        link_download_url_ref = 'http://play.baidu.com/?__m=mboxCtrl.playSong&__a={song_id}&__o=/||sugIcon&fr=-1||www.baidu.com'
        ref = link_download_url_ref.format(song_id=self.baidu_song_id);
        header = {
                  'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    #     'Accept-Encoding':'gzip,deflate,sdch',
                  'Accept-Language':'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4',
                  'Cache-Control':'max-age=0',
                  'Connection':'keep-alive',
                  'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
                  'Cookie':'BDRCVFR[T77Y7lc0xct]=rJZwba6_rOCfAF9pywd; LUP=bt%3D1397355264%26email%3Dicandiio%2540hotmail.com%26f%3D1%26loginname%3Dicandiio%2540hotmail.com%26mobile%3D%26nick%3DJustin%25C1%25F7%26nickname%3D%25E6%25B5%25AA%25E8%25BF%25B9%25E6%25B5%2581%26uid%3D2184607024%26user%3Dicandiio%2540hotmail.com%26ut%3D2014-03-11%2B15%253A48%253A59; LUE=5a05ca34a19cbb2ed23dbc1c6e78adee; LUE2=iQmunLtBTaOgI6ltnvxC8BcuoFcKQWz1IbbW2s7ZyyJQja6R1%2FvqupDXPbfDZv0dIZGP7XUv8TqF%2FjANB2NcEXPUhDiBcOexLVdmK1pLTyXHmPlKCRiz83U38Px2cBquuNs9WlyZRMSjhJrpy5gTKjZBjxv2PM2bVh862rTTz64DUEPCiPhsSAChucz5AwNu8mjiaHYtnGjGJfhQ7hGtmC64Q3L7ai3moxTQh1pEKMLySjbF7zhKeTkeZ%2BBH3%2Ft25b4tjghT43qs774b85kZzsqQSvHMmw5EcUEAOy9GNwC0Iw4%2B5ygeJ6aTZkdI%2F9IORdQkcPkD6D3LtRRZwxMedie5FelHSVptPj0GvJ28zshtcUFpsKWI%2B3fXhajRpL0E; BDREFER=%7Burl%3A%22http%3A//finance.baidu.com/%22%2Cword%3A%22%22%7D; locale=zh; BDRCVFR[feWj1Vr5u3D]=I67x6TjHwwYf0; cflag=65535:1; BDRCVFR[ZkFHqMHDBDs]=oJc051W-SeffjbYrjRvPjmsgv99Udqs; BAIDUID=0B67D89FEBD0132E4D098B414E9B1CEA:FG=1; H_PS_PSSID=1451_5223_6155_6023_4759_6017_6258_5857_6270; Hm_lvt_2b0f0945031c52df2a103f3ed5d7c3aa=1398520122,1398520146,1398520448,1398520492; Hm_lpvt_2b0f0945031c52df2a103f3ed5d7c3aa=1398520492; Hm_lvt_d0ad46e4afeacf34cd12de4c9b553aa6=1396952669; Hm_lpvt_d0ad46e4afeacf34cd12de4c9b553aa6=1398520493',
                  'Host':'play.baidu.com',
                  'Referer':ref,
                  'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36'
        }
        params = {'songIds':str(self.baidu_song_id), 'hq':1, 'type':'m4a,mp3', 'rate':'', 'pt':0, 'flag':-1, 's2p':-1, 'prerate':-1, 'bwt':-1, 'dur':-1, 'bat':-1, 'bp':-1, 'pos':-1, 'auto':-1}
        
        link_download_url = 'http://play.baidu.com/data/music/songlink'
        req = urllib2.Request(url=link_download_url, data=urllib.urlencode(params), headers=header)
        json_str = urllib2.urlopen(req).read();
        # {"errorCode":22000,"data":{"time":3600,"xcode":"3d0673fda3d0f277c938e504f7d93823","songList":[{"queryId":"1102942","status":0,"songId":1102942,"songName":"\u5341\u5e74","artistId":"87","artistName":"\u9648\u5955\u8fc5","albumId":1101844,"albumName":"The Best Moment","lrcLink":"\/data2\/lrc\/13767709\/13767709.lrc","linkCode":22000,"linkinfo":{"128":{"songLink":"http:\/\/yinyueshiting.baidu.com\/data2\/music\/41535844\/1102942165600128.mp3?xcode=34efea5c26ba648721a976890c57f8bfeaf330620dd9cc0f","showLink":"http:\/\/yinyueshiting.baidu.com\/data2\/music\/41535844\/1102942165600128.mp3?xcode=34efea5c26ba648721a976890c57f8bfeaf330620dd9cc0f","format":"mp3","time":205,"size":3288630,"rate":128,"enhancement":"0.959999"},"320":{"songLink":"http:\/\/yinyueshiting.baidu.com\/data2\/music\/31629381\/1102942165600320.mp3?xcode=34efea5c26ba6487fa64ce40a33938c963d634ffc844a8f9","showLink":"http:\/\/yinyueshiting.baidu.com\/data2\/music\/31629381\/1102942165600320.mp3?xcode=34efea5c26ba6487fa64ce40a33938c963d634ffc844a8f9","format":"mp3","time":206,"size":8231680,"rate":320,"enhancement":"1.959999"},"321":{"songLink":"http:\/\/yinyueshiting.baidu.com\/data2\/music\/52256955\/1102942165600321.mp3?xcode=34efea5c26ba6487757ce18ec6b454f4ed7d600bef7e7c32","showLink":"http:\/\/yinyueshiting.baidu.com\/data2\/music\/52256955\/1102942165600321.mp3?xcode=34efea5c26ba6487757ce18ec6b454f4ed7d600bef7e7c32","format":"mp3","time":206,"size":8255235,"rate":320,"enhancement":""}},"version":"","copyType":1,"enhancement":"0.959999"}]}}
        if (json_str != '') :
            jo = json.loads(json_str)
            if len(jo['data']['songList']) > 0:
                jsong = jo['data']['songList'][0]
                self.baidu_lrc_url = 'http://play.baidu.com' + jsong['lrcLink']
                if len(jo['data']['songList'][0]['linkinfo']) > 0:
                    if len(jo['data']['songList'][0]['linkinfo']['128']) > 0:
                        slink = jo['data']['songList'][0]['linkinfo']['128']['songLink']
                        self.baidu_mp3_url = slink;
                        return;
                    if len(jo['data']['songList'][0]['linkinfo']['320']) > 0:
                        slink = jo['data']['songList'][0]['linkinfo']['128']['songLink']
                        self.baidu_mp3_url = slink;
                        return
    
    def downloadfile(self):
        util.lrc_download_handler(self.baidu_lrc_url, self.copyright_id)
        util.mp3_download_handler(self.baidu_mp3_url, self.copyright_id)
            
# baidu = Baidu('BAIDU', '十年', '陈奕迅')
# baidu.search()
# baidu.extract_download_url()
# baidu.downloadfile()
# 
# print baidu;
